﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using thousandclear.Data;
using thousandClear.Areas.Shop.Models;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Shop.Controllers
{
    public class AddressController : BaseController
    {
        // GET: Shop/Address
        public ActionResult Index(string openid, string order, string code, string state)
        {
            AppSetting setting = new AppSetting();
            try
            {
                
                ViewBag.openid = openid;
                ViewBag.orderID = order;
                if (string.IsNullOrEmpty(openid))
                {
                    openid = GetOpenId(code).openid;

                    if (string.IsNullOrEmpty(openid))
                    {
                        Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed78d8fdb0030e29&redirect_uri=http%3a%2f%2f{0}%2fshop%2fAddress&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                    }
                }
                using (var db = new qianjingEntities())
                {

                    var Provinces = db.D_Angent.Where(a => a.RowStatus == 1 && a.datLevel == 1).ToList();
                    ViewBag.Provinces = JsonConvert.SerializeObject(Provinces);

                }
            }
            catch (Exception ex)
            {
                Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed78d8fdb0030e29&redirect_uri=http%3a%2f%2f{0}%2fshop%2fAddress&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
            }
            
            return View();
        }

        //HttpGet: Shop/Address
        [HttpGet]
        public String changePlace(long id)
        {
            var query = "";
            using (var db = new qianjingEntities())
            {
                query = JsonConvert.SerializeObject(db.D_Angent.Where(a => a.datDATID == id && a.RowStatus == 1).ToList());
            }
            return query;
        }
        //HttpGet: Shop/Address
        [HttpGet]
        public int SelectTime(string id,string time,string day)
        {
            UtilNS.Util.WriteLog(System.DateTime.Now + "SelectTime::" + time + "dat::" + day);
            int i = 1;
            string time2 = "0" + time;
            UtilNS.Util.WriteLog(System.DateTime.Now + "Time2::" + time2);

            string yy = day.Substring(0, 4) + "-" + day.Substring(4, 2) + "-" + day.Substring(6, 2);
            var tt = DateTime.Parse(yy);

            


            using (var db = new qianjingEntities())
            {
                var query = db.T_Order.FirstOrDefault(a => a.toSerialNo == id);
                var csm = db.O_Goods.FirstOrDefault(a => a.OGSID == query.toOGID);
                UtilNS.Util.WriteLog(System.DateTime.Now + "csm.ogsType::" + csm.ogsType);

                DateTime f1 = new DateTime(2017, 1, 22);
                DateTime f2 = new DateTime(2017, 2, 5);

                //1代表单次
                if (csm.ogsType == 1)
                {
                    if (tt.DayOfWeek == DayOfWeek.Sunday)
                    {
                        i = 0;
                    }
                    else
                    {
                        var record = db.v_Order.FirstOrDefault(a => (a.osaTimeslot == time || a.osaTimeslot == time2) && a.osaStartDay == day && a.ogsType == 1 && a.RowStatus != 0 && a.RowStatus != 2 && a.RowStatus != 4);
                        if (record != null)
                        {
                            i = 2;
                        }
                    }
                }
                //7代表活动体验，小时活动
                else if (csm.ogsType == 7)
                {
                    if (tt >= f1 && tt <= f2)
                    {
                        i = 10;
                    }
                    else
                    {
                        var record = db.v_Order.Where(a => (a.osaTimeslot == time || a.osaTimeslot == time2) && a.osaStartDay == day && a.ogsType == 7 && a.RowStatus != 0 && a.RowStatus != 2 && a.RowStatus != 4);
                        if (record.Count() >= 2)
                        {
                            i = 2;
                        }
                    }
                }
                //5代表66元擦玻璃
                else if (csm.ogsType == 5)
                {
                    UtilNS.Util.WriteLog("开始单项::" + day);
                    bool isqwe = false;
                    if (query.toItemsGift != null)
                    {
                        if (!string.IsNullOrEmpty(query.toItemsGift))
                        {
                            UtilNS.Util.WriteLog("成功单项::" + query.toItemsGift);
                            var final = query.toItemsGift.Split(',').ToList();
                            foreach (var itemID in final)
                            {
                                UtilNS.Util.WriteLog("进到循环::" + itemID);
                                if (itemID.ToString().Trim() == "35")
                                {
                                    isqwe = true;
                                    UtilNS.Util.WriteLog("擦玻璃::" + itemID);
                                    if (tt.CompareTo(DateTime.Parse("2016-09-30")) > 0)
                                    {
                                        UtilNS.Util.WriteLog("擦玻璃日期不对::" + itemID);
                                        i = 4;
                                        break;
                                    }
                                    else
                                    {
                                        UtilNS.Util.WriteLog("擦玻璃活动开始::" + itemID);
                                        i = 5;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    

                    if (isqwe)
                    {
                        var record = db.v_Order.FirstOrDefault(a => (a.osaTimeslot == time || a.osaTimeslot == time2) && a.osaStartDay == day && a.ogsType == 5 && a.RowStatus != 0 && a.RowStatus != 2 && a.RowStatus != 4);
                        if (record != null)
                        {
                            i = 2;
                        }
                    }
                    else
                    {
                        if (tt >= f1 && tt <= f2)
                        {
                            i = 10;
                        }
                        else if (tt.DayOfWeek == DayOfWeek.Sunday)
                        {
                            i = 0;
                        }
                        else
                        {
                            var record = db.v_Order.FirstOrDefault(a => (a.osaTimeslot == time || a.osaTimeslot == time2) && a.osaStartDay == day && a.ogsType == 5 && a.RowStatus != 0 && a.RowStatus != 2 && a.RowStatus != 4);
                            if (record != null)
                            {
                                i = 2;
                            }
                        }
                    }
                }
            }

            return i;
        }


        // POST: Shop/Address
        [HttpPost]
        public ActionResult Index(string data)
        {
            try
            {
                AppSetting setting = new AppSetting();
                var post = JObject.Parse(data);
                string orderID = post["orderID"].Value<string>();
                string remark = post["remark"].Value<string>();
                string receiveMobile = post["receiveMobile"].Value<string>();
                string receiveMan = post["receiveMan"].Value<string>();
                string receiveAddress = post["receiveAddress"].Value<string>()==""
                    ? ("玲珑湾"+post["receiveSixAddress"].Value<string>())
                    : post["receiveAddress"].Value<string>();


                int SelectBlock = post["SelectBlock"].Value<int>();
                string openid = post["openid"].Value<string>();
                string time = post["time"].Value<string>();
                string day = post["day"].Value<string>();
                UtilNS.Util.WriteLog("day::" + day);
                List<O_Address> address = new List<O_Address>();
                using (var db = new qianjingEntities())
                {
                    int i = 0;
                    int oaid = 0;
                    var addressList = db.O_Address.Where(a=>a.RowStatus==1).ToList();
                    var order = db.T_Order.FirstOrDefault(a => a.toSerialNo == orderID);

                   

                    
                    //UtilNS.Util.WriteLog("oasNo::" + oasNo);
                    //2016-07-26 为排查同地址下单，时间未更新问题，注释以下语句
                    //foreach (var item in addressList) {
                    //    if (item.oasAddressDetail.Trim().ToString() == receiveAddress.Trim().ToString() && item.oasDATID == SelectBlock)
                    //    {
                    //        i = 1;
                    //        oaid =Convert.ToInt16(item.OASID);
                    //        break;
                    //    }
                        
                    //}
                    UtilNS.Util.WriteLog("day::" + day);
                    if (i == 0)
                    {
                        int times = Convert.ToInt16(db.O_Goods.FirstOrDefault(a => a.OGSID == order.toOGID).ogsSignTime);
                        DateTime _temp = new DateTime();
                        var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                        DateTime.TryParseExact(day, "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out _temp);
                        //UtilNS.Util.WriteLog("oasNo::" + oasNo);
                        db.O_Address.Add(new O_Address
                        {
                            oasDATID = SelectBlock,
                            oasName = receiveMan,
                            osaPhone = receiveMobile,
                            oasAddressDetail = receiveAddress,
                            osaTimeslot = time,
                            oasOCID = Convert.ToInt16(customer.OCID),
                            RowStatus = 1,
                            CreatedDate = DateTime.Now,
                            osaStartDay = day,
                            //oasNo = oasNo,
                            osaEndDay = _temp.AddMonths(times).ToString("yyyyMMdd"),
                        });


                        db.SaveChanges();
                        var toOAID = db.O_Address.OrderByDescending(a => a.CreatedDate).FirstOrDefault(a => a.oasOCID == customer.OCID).OASID;
                        order.RowStatus = 4;
                        order.toOAID = Convert.ToInt16(toOAID);
                        order.toRemark = remark;
                        db.SaveChanges();
                    }
                    else {
                        order.RowStatus = 4;
                        order.toOAID = oaid;
                        order.toRemark = remark;
                        db.SaveChanges();

                    }
                }

            RouteValueDictionary dicgt = new RouteValueDictionary();
                dicgt.Add("openid", openid);
                dicgt.Add("order", orderID);

            return RedirectToAction("../Order/Index", dicgt);
            }
            catch (Exception ex)
            {
                UtilNS.Util.WriteLog("ex::" + ex);
            }
            return RedirectToAction("../Order/Index");


        }
    }
}